print("客服号专用脚本启动")
-- 客服号专用脚本：轮询服务器获取hintType消息并说话

-- 配置参数
local baseUrl = "https://u7playearn.shopwegame.com/dev-api/play-earn/api/order"
local authSecret = "8f9dbe334ca364eac2b18ca437fde25d"
local pollInterval = 5 -- 轮询间隔（秒）
local maxRetries = 3 -- 最大重试次数

-- 获取当前玩家名
local LocalPlayerName = game.Players.LocalPlayer.Name
local HttpService = game:GetService("HttpService")

-- 说话功能：将消息作为聊天内容发送
local TextChatService = game:GetService("TextChatService")

local function getGeneralChannel()
    local ok, channel = pcall(function()
        if TextChatService.ChatVersion == Enum.ChatVersion.TextChatService then
            local channels = TextChatService:FindFirstChild("TextChannels")
            return channels and channels:FindFirstChild("RBXGeneral")
        end
        return nil
    end)
    if ok then return channel end
end

local function say(message)
    if type(message) ~= "string" or message == "" then return end
    -- 新版 TextChat（仅在开启新聊天系统时可用）
    local channel = getGeneralChannel()
    if channel then
        pcall(function()
            channel:SendAsync(string.sub(message, 1, 200))
        end)
    end
end

-- HTTP请求函数
local function httpGet(url)
    local success, result = pcall(function()
        return game:HttpGet(url, true)
    end)
    if success then
        return result
    else
        print("HTTP请求失败：" .. url .. " - " .. tostring(result))
        return nil
    end
end

-- 日志函数
local function log(message)
    local logMessage = string.format("[%s] %s", os.date("%Y-%m-%d %H:%M:%S"), tostring(message))
    print(logMessage)
    
    -- 记录到本地文件
    local success, err = pcall(function()
        appendfile("customer_service_log.txt", logMessage .. "\n")
    end)
    if not success then
        pcall(function()
            writefile("customer_service_log.txt", logMessage .. "\n")
        end)
    end
end

-- 获取客服消息的API接口
local function getCustomerServiceMessages()
    -- 构建查询URL，添加客服号标识
    local url = string.format("%s/customer-service?authSecret=%s&robloxUserName=%s&type=hint", 
                             baseUrl, authSecret, LocalPlayerName)
    
    local success, response = pcall(function()
        local result = httpGet(url)
        if not result then
            return nil, "HTTP request failed"
        end
        
        local result_d = HttpService:JSONDecode(result)
        if result_d.code == 200 then
            return result_d.data
        else
            return nil, "API returned error code: " .. tostring(result_d.code)
        end
    end)
    
    if not success then
        log("getCustomerServiceMessages 请求失败: " .. tostring(response))
        return nil
    end
    
    return response
end
-- 交易提示消息（仅在指定的5个位置发送）
local function sendTradeHint(hintType)
    if hintType == 1 then
        -- say("请接受交易申请进行交易")
        say("Plz accept the trade request.")
    elseif hintType == 2 or hintType == 3 then
        -- say("请放置正确的物品进行交易")
        say("Plz put the correct items to trade")
    elseif hintType == 4 then
        -- say("请接受交易申请进行交易")
        say("Plz accept the trade request.")
    elseif hintType == 5 then
        -- say("交易失败，请再次在网站提交售卖请求")
        say("Trade failed, plz quit the server and sumbit the trading request in site again.")
    end
end
-- 处理hintType消息
local function processHintMessage(hintData)
    if not hintData or not hintData.hintType then
        return
    end
    
    local hintType = hintData.hintType
    local orderMainId = hintData.orderMainId
    local user = hintData.user
    
    log(string.format("收到hintType消息: %d, 订单ID: %s, 用户: %s", 
                     hintType, tostring(orderMainId), tostring(user)))
    
    -- 根据hintType处理不同的消息
    sendTradeHint(hintType)
    if hintType > 5 then
        log("未知的hintType: " .. tostring(hintType))
    end
end

-- 标记已处理的消息（避免重复处理）
local processedMessages = {}

-- 检查消息是否已处理
local function isMessageProcessed(messageId)
    return processedMessages[messageId] ~= nil
end

-- 标记消息为已处理
local function markMessageProcessed(messageId)
    processedMessages[messageId] = os.time()
    
    -- 清理过期的处理记录（超过1小时）
    local now = os.time()
    for id, timestamp in pairs(processedMessages) do
        if now - timestamp > 3600 then
            processedMessages[id] = nil
        end
    end
end

-- 主轮询循环
local function startPolling()
    log("客服号开始轮询服务器消息...")
    
    while true do
        local retryCount = 0
        local success = false
        
        -- 重试机制
        while retryCount < maxRetries and not success do
            local messages = getCustomerServiceMessages()
            
            if messages then
                success = true
                
                -- 处理消息列表
                if type(messages) == "table" then
                    for _, messageData in ipairs(messages) do
                        local messageId = messageData.id or messageData.messageId
                        
                        -- 检查是否已处理过
                        if messageId and not isMessageProcessed(messageId) then
                            processHintMessage(messageData)
                            markMessageProcessed(messageId)
                        end
                    end
                elseif type(messages) == "table" and messages.hintType then
                    -- 单个消息
                    local messageId = messages.id or messages.messageId
                    if messageId and not isMessageProcessed(messageId) then
                        processHintMessage(messages)
                        markMessageProcessed(messageId)
                    end
                end
                
            else
                retryCount = retryCount + 1
                if retryCount < maxRetries then
                    log("获取消息失败，第" .. retryCount .. "次重试...")
                    task.wait(2) -- 重试前等待2秒
                end
            end
        end
        
        if not success then
            log("获取消息失败，已达到最大重试次数")
        end
        
        -- 等待下次轮询
        task.wait(pollInterval)
    end
end

-- 启动客服号服务
log("客服号脚本初始化完成，玩家: " .. LocalPlayerName)
task.spawn(startPolling)
